package com.dpc.springbootvalidation.controller;

import com.dpc.common.ResponseResult;
import com.dpc.springbootvalidation.entity.UserParam;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("user")
@Validated
public class UserController {

    /**
     * 常规参数校验.
     *
     * @param userParam user param
     * @return user
     */
    @PostMapping("/add")
   public ResponseEntity<String> addo(@Valid @RequestBody UserParam userParam, BindingResult bindingResult) {
       if (bindingResult.hasErrors()) {
          List<ObjectError> errors = bindingResult.getAllErrors();
          errors.forEach(p -> {
              FieldError fieldError = (FieldError) p;
              System.out.println(fieldError.getField());
               System.out.println(fieldError.getObjectName());
               System.out.println(fieldError.getDefaultMessage());
           });
            return ResponseEntity.badRequest().body("invalid parameter");
       }
        return ResponseEntity.ok("");
   }


    /**
     * 分组校验     参数遇到新增和修改既可以为空也可以不为空的情况
     * @param userParam
     * @param bindingResult
     * @return
     */

    @PostMapping(value = "/valid/add")
    public String add(@Validated(value = ValidGroup.Crud.Create.class) @RequestBody UserParam userParam, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            List<ObjectError> errors = bindingResult.getAllErrors();
            errors.forEach(p -> {
                FieldError fieldError = (FieldError) p;
                System.out.println(fieldError.getField());
                System.out.println(fieldError.getObjectName());
                System.out.println(fieldError.getDefaultMessage());
            });
        }
        return "test3 valid success";
    }

    @PostMapping(value = "/valid/update")
    public String update(@Validated(value = ValidGroup.Crud.Update.class) @RequestBody UserParam userParam, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            List<ObjectError> errors = bindingResult.getAllErrors();
            errors.forEach(p -> {
                FieldError fieldError = (FieldError) p;
                System.out.println(fieldError.getField());
                System.out.println(fieldError.getObjectName());
                System.out.println(fieldError.getDefaultMessage());
            });
        }
        return "test4 valid success";
    }
}
